<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="searchForm" :inline="true" :model="searchFilter">
        <el-form-item label="ID" prop="id"><el-input v-model="searchFilter.id" clearable placeholder="请输入ID" /></el-form-item>
        <el-form-item label="用户名" prop="username"><el-input v-model="searchFilter.username" clearable placeholder="请输入用户名" /></el-form-item>
        <el-form-item label="昵称" prop="nickname"><el-input v-model="searchFilter.nickname" clearable placeholder="请输入昵称" /></el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchFilter.status" clearable placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-circle-close" @click="clear">清除</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" empty-text>
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column prop="avatar" label="头像" width="60">
        <template slot-scope="scope">
          <el-avatar :size="30" :src="scope.row.avatar ? scope.row.avatar : defaultAvatar" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="nickname" label="昵称" width="180" />
      <el-table-column prop="status" label="性别" width="70">
        <template slot-scope="scope">
          <el-tag effect="dark" :type="genderMap[scope.row.gender]['tag']">{{ genderMap[scope.row.gender]['label'] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="70">
        <template slot-scope="scope">
          <el-tag effect="dark" :type="statusMap[scope.row.status - 1]['tag']">{{ statusMap[scope.row.status - 1]['label'] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="电子邮箱" />
      <el-table-column prop="mobile" label="手机号" />
      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column prop="updated_at" label="更新时间" />
      <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" @click="handleAssign(row)">分配权限</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="searchFilter.current_page" :limit.sync="searchFilter.per_page" @pagination="getList" />

    <el-dialog :title="dialogTitleMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username"><el-input v-model="temp.username" maxlength="40" placeholder="请输入用户名" /></el-form-item>
        <el-form-item label="昵称" prop="nickname"><el-input v-model="temp.nickname" maxlength="40" placeholder="请输入昵称" /></el-form-item>
        <el-form-item label="密码" prop="password"><el-input v-model="temp.password" maxlength="30" show-password placeholder="请输入密码" /></el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-for="item in genderMap" :key="item.key" v-model="temp.gender" :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" action="" :auto-upload="false" :show-file-list="false" :on-change="avatarUploadChange" accept="image/*">
            <img v-if="temp.avatar" :src="temp.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="邮箱" prop="email"><el-input v-model="temp.email" maxlength="100" placeholder="请输入邮箱" /></el-form-item>
        <el-form-item label="手机号" prop="mobile"><el-input v-model="temp.mobile" maxlength="11" placeholder="请输入手机号" /></el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="temp.status" active-color="#13ce66" :active-value="1" :inactive-value="2" inactive-color="#ff4949" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :close-on-click-modal="false" :visible.sync="dialogAssignFormVisible">
      <el-transfer v-model="assignedRoles" :data="allRoles" :titles="['未分配的角色', '已分配的角色']" :button-texts="['删除角色', '添加角色']" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignFormVisible = false">取消</el-button>
        <el-button type="primary" @click="assignRoles()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      custom-class="cropper-dialog"
      title="头像剪裁"
      :visible.sync="dialogCropperVisible"
      width="400px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="cancelCropAvatar"
    >
      <div class="cropper-content">
        <vue-cropper ref="cropper" auto-crop fixed-box :info="false" :output-size="0.6" :auto-crop-width="300" :auto-crop-height="300" :img="tmpAvatar" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelCropAvatar">取 消</el-button>
        <el-button type="primary" @click="cropAvatar">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { adminUserList, createAdminUser, updateAdminUser, deleteAdminUser, assignRoles, getUserRoles } from '@/api/admin-user'
import { VueCropper } from 'vue-cropper'
import Pagination from '@/components/Pagination'
export default {
  name: 'AdminUserList',
  components: { Pagination, VueCropper },
  data() {
    return {
      defaultAvatar: require('@/assets/images/common/default-avatar.gif'),
      listLoading: true,
      total: 0,
      list: [],
      tmpAvatar: '',
      dialogCropperVisible: false,
      searchFilter: {
        id: '',
        username: '',
        nickname: '',
        status: '',
        current_page: 1,
        per_page: 20
      },
      genderMap: [
        {
          label: '保密',
          tag: 'info',
          value: 0
        },
        {
          label: '男',
          tag: '',
          value: 1
        },
        {
          label: '女',
          tag: 'danger',
          value: 2
        }
      ],
      statusMap: [
        {
          label: '启用',
          tag: 'success',
          value: 1
        },
        {
          label: '禁用',
          tag: 'danger',
          value: 2
        }
      ],
      dialogAssignFormVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      dialogTitleMap: {
        update: '编辑',
        create: '创建'
      },
      temp: {
        id: 0,
        username: '',
        nickname: '',
        password: '',
        avatar: '',
        gender: 0,
        email: '',
        mobile: '',
        status: 1
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 2, message: '用户名不能少于2位', trigger: ['blur', 'change'] },
          { max: 40, message: '用户名不能大于40位', trigger: ['blur', 'change'] }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: ['blur', 'change'] },
          { min: 2, message: '昵称不能少于2位', trigger: ['blur', 'change'] },
          { max: 40, message: '昵称不能大于40位', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 6, message: '密码不能少于6位', trigger: ['blur', 'change'] },
          { max: 30, message: '密码不能大于30位', trigger: ['blur', 'change'] }
        ],
        email: [{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }],
        mobile: [{ required: true, message: '请输入手机号', trigger: ['blur', 'change'] }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }]
      },
      userId: 0,
      assignedRoles: [],
      allRoles: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        id: 0,
        username: '',
        nickname: '',
        password: '',
        avatar: '',
        gender: 0,
        email: '',
        mobile: '',
        status: 1
      }
    },
    getList() {
      this.listLoading = true
      adminUserList(this.searchFilter).then(response => {
        this.list = response.data.list
        this.searchFilter.current_page = response.data.pagination.current_page
        this.searchFilter.per_page = response.data.pagination.per_page
        this.total = response.data.pagination.total
        this.listLoading = false
      })
    },
    search() {
      this.getList(this.searchFilter)
    },
    clear() {
      this.$refs['searchForm'].resetFields()
      this.getList(this.searchFilter)
    },
    avatarUploadChange(file) {
      this.dialogCropperVisible = true
      this.tmpAvatar = URL.createObjectURL(file.raw)
    },
    cancelCropAvatar() {
      this.dialogCropperVisible = false
      this.tmpAvatar = ''
    },
    cropAvatar() {
      this.$refs.cropper.getCropData(data => {
        this.dialogCropperVisible = false
        this.temp.avatar = data
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.rules.password[0].required = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.rules.password[0].required = false
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdminUser(row).then(res => {
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1)
          this.$notify({
            title: '成功',
            message: res.message,
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleAssign(row) {
      this.userId = row.id
      this.allRoles = []
      this.assignedRoles = []
      getUserRoles(this.userId).then(res => {
        this.dialogAssignFormVisible = true
        res.data.allRoles.forEach(item => {
          this.allRoles.push({
            key: item.id,
            label: `${item.name}`,
            disabled: false
          })
        })
        this.assignedRoles = res.data.assignedRoles
      })
    },
    assignRoles() {
      assignRoles({ id: this.userId, roles: this.assignedRoles }).then(res => {
        this.dialogAssignFormVisible = false
        this.$notify({
          title: '成功',
          message: res.message,
          type: 'success',
          duration: 2000
        })
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createAdminUser(this.temp).then(res => {
            this.list.unshift(res.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: res.message,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateAdminUser(this.temp).then(res => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, res.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: res.message,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }
  }
}
</script>

<style></style>
